package com.lagou.muticodec;

import com.lagou.util.HexUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * 客户端处理类
 */
public class NettyClientHandler implements ChannelInboundHandler {

    /**
     * 通道就绪事件
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 3; i++) {
            ctx.writeAndFlush(Unpooled.copiedBuffer("{\"fver\":\"YED_DTU_1.1.0_luat_v3029_rda8910_tts_novolte_float\",\"iccid\":\"898604901920C1599550\",\"imei\":\"868739058142740\",\"csq\":31}",CharsetUtil.UTF_8));
            ctx.writeAndFlush(Unpooled.copiedBuffer("{\"fver\":\"YED_DTU_1.1.0_luat_v3029_rda8910_tts_novolte_float\",\"iccid\":\"898604901920C1599550\"",CharsetUtil.UTF_8));
            ctx.writeAndFlush(Unpooled.copiedBuffer(",\"imei\":\"868739058142740\",\"csq\":31}",CharsetUtil.UTF_8));
            String hexString="0F03180102000009C41388FEF9294953B4FF0200020003000000022AB50D0A";
            byte[] bt= HexUtil.hexStringToByteArray(hexString);
            System.out.println("bt.length:"+bt.length);
            ctx.writeAndFlush(Unpooled.copiedBuffer(bt));
            String hexString1="010101010D0A";
            byte[] bt1= HexUtil.hexStringToByteArray(hexString1);
            System.out.println("bt1.length:"+bt1.length);
            ctx.writeAndFlush(Unpooled.copiedBuffer(bt1));
        }
    }

    /**
     * 通道读就绪事件
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        System.out.println("服务端发送的消息:" + byteBuf.toString(CharsetUtil.UTF_8));
    }


    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {

    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

    }

    @Override
    public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }
}
